<template>
  <view class="my-approval-send-page">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-left" @click="goBack">
        <u-icon name="arrow-left" color="#ffffff" size="24"></u-icon>
      </view>
      <view class="nav-center">
        <text class="nav-title">已审批发文</text>
      </view>
      <view class="nav-right"></view>
    </view>

    <!-- 搜索区域 -->
    <view class="search-section">
      <view class="search-header" @click="toggleSearchExpand">
        <view class="search-header-left">
          <u-icon name="search" size="18" color="#1678ff"></u-icon>
          <text class="search-header-title">筛选条件</text>
        </view>
        <view class="search-header-right">
          <text class="expand-text">{{ searchExpanded ? '收起' : '展开' }}</text>
          <u-icon
            :name="searchExpanded ? 'arrow-up' : 'arrow-down'"
            size="16"
            color="#999"
          ></u-icon>
        </view>
      </view>

      <view class="search-form" v-show="searchExpanded">
        <view class="form-row">
          <input class="search-input" v-model="searchForm.title" placeholder="请输入公文标题" />
        </view>

        <!-- 时间筛选 -->
        <view class="form-row time-filter-row">
          <text class="filter-label">时间筛选</text>
          <view class="time-picker-group">
            <picker
              mode="selector"
              :range="timeModeOptions"
              :value="timeModeIndex"
              @change="handleTimeModeChange"
              class="time-mode-picker"
            >
              <view class="picker-input mode-picker">
                <text>{{ timeModeOptions[timeModeIndex] }}</text>
                <u-icon name="arrow-down" size="12" color="#999" />
              </view>
            </picker>
            <picker
              :mode="pickerMode"
              :value="timeValue"
              @change="handleTimeChange"
              :start="startDate"
              :end="endDate"
              class="time-value-picker"
            >
              <view class="picker-input value-picker">
                <text class="time-text" :class="{ placeholder: !timeDisplayText }">
                  {{ timeDisplayText || '选择时间' }}
                </text>
                <u-icon name="calendar" color="#1678ff" size="16" />
              </view>
            </picker>
            <view class="clear-btn" v-if="timeValue" @click.stop="clearTime">
              <u-icon name="close-circle-fill" size="16" color="#999" />
            </view>
          </view>
        </view>

        <view class="search-buttons">
          <text class="search-btn" @click="handleSearch">查询</text>
          <text class="reset-btn" @click="handleReset">重置</text>
        </view>
      </view>
    </view>

    <!-- 列表区域 -->
    <view class="list-section">
      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <text class="loading-text">加载中...</text>
      </view>

      <scroll-view
        class="approval-list"
        scroll-y
        :show-scrollbar="false"
        v-else-if="approvalList.length > 0"
      >
        <view
          class="approval-item"
          v-for="item in approvalList"
          :key="item.id"
          @click="handleView(item)"
        >
          <view class="item-header">
            <view class="item-title">
              <text class="title-text">{{ item.title || '无标题' }}</text>
              <view
                :class="[
                  item.bizCategory === '党务发文' ? 'category-badge-party' : 'category-badge',
                ]"
                v-if="item.bizCategory"
              >
                <text class="badge-text">{{ item.bizCategory }}</text>
              </view>
            </view>
            <text class="item-time">{{ formatDateTime(item.createdAt) }}</text>
          </view>
          <view class="item-content">
            <text class="item-desc">拟稿部门：{{ item.applicantDeptName || '未知' }}</text>
            <text class="item-desc">拟稿人：{{ item.applicantName || '未知' }}</text>
            <text class="item-desc">审批步骤：{{ (item as any).currentStepName || '-' }}</text>
          </view>
          <view class="item-footer">
            <view class="item-info">
              <text class="info-text"
                >审批时间：{{ formatDateTime((item as any).approvedAt || item.createdAt) }}</text
              >
            </view>
            <view class="item-actions">
              <text class="action-btn" @click.stop="handleView(item)">查看</text>
            </view>
          </view>
        </view>
      </scroll-view>

      <view class="empty-state" v-else>
        <text class="empty-icon">📋</text>
        <text class="empty-text">暂无审批记录</text>
      </view>

      <!-- 分页固定底部 -->
      <view class="pagination-section" v-if="pagination.total > 0">
        <view class="pagination-info">
          <text
            >共{{ pagination.total }}条，第{{ pagination.current }}/{{
              Math.ceil(pagination.total / pagination.size)
            }}页</text
          >
        </view>
        <view class="pagination-buttons">
          <text
            class="page-btn"
            :class="{ disabled: pagination.current <= 1 }"
            @click="handlePrevPage"
          >
            上一页
          </text>
          <text
            class="page-btn"
            :class="{
              disabled: pagination.current >= Math.ceil(pagination.total / pagination.size),
            }"
            @click="handleNextPage"
          >
            下一页
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
  getApprovalDocumentRecords,
  type DocumentQueryParams,
  type DocumentItem,
} from '@/Api/document'

// 搜索展开/收起状态
const searchExpanded = ref(false)

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = ref({
  title: '',
})

// 时间筛选
const timeModeOptions = ['年', '月', '日']
const timeModeIndex = ref(2) // 默认选择"日"
const timeValue = ref<string>('')
const startDate = ref('2020-01-01')
const endDate = ref('2099-12-31')

// 审批记录列表
const approvalList = ref<DocumentItem[]>([])

// 分页
const pagination = ref({
  current: 1,
  size: 20,
  total: 0,
})

// 返回上一页
const goBack = () => {
  const pages = getCurrentPages()
  if (pages.length <= 1) {
    uni.reLaunch({
      url: '/pages/index/index',
    })
  } else {
    uni.navigateBack({
      delta: 1,
    })
  }
}

// 切换搜索展开/收起
const toggleSearchExpand = () => {
  searchExpanded.value = !searchExpanded.value
}

// Picker模式
const pickerMode = computed(() => {
  if (timeModeIndex.value === 0) return 'date' // 年选择
  if (timeModeIndex.value === 1) return 'date' // 月选择
  return 'date' // 日选择
})

// 时间显示文本
const timeDisplayText = computed(() => {
  if (!timeValue.value) return ''

  if (timeModeIndex.value === 0) {
    // 年
    return `${timeValue.value.substring(0, 4)}年`
  } else if (timeModeIndex.value === 1) {
    // 月
    const parts = timeValue.value.split('-')
    return `${parts[0]}年${parts[1]}月`
  } else {
    // 日
    const parts = timeValue.value.split('-')
    return `${parts[0]}年${parts[1]}月${parts[2]}日`
  }
})

// 时间模式改变
const handleTimeModeChange = (e: any) => {
  timeModeIndex.value = e.detail.value
  timeValue.value = '' // 清空已选时间
}

// 时间选择器改变
const handleTimeChange = (e: any) => {
  timeValue.value = e.detail.value
}

// 清空时间
const clearTime = () => {
  timeValue.value = ''
}

// 搜索处理
const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  searchForm.value.title = ''
  timeModeIndex.value = 2
  timeValue.value = ''
  pagination.value.current = 1
  loadData()
}

// 查看详情
const handleView = (item: any) => {
  uni.navigateTo({
    url: `/pages/document/send/detail?id=${item.id}&source=view`,
  })
}

// 格式化日期时间
const formatDateTime = (dateTime?: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}/${month}/${day}`
}

// 分页处理
const handlePrevPage = () => {
  if (pagination.value.current > 1) {
    pagination.value.current--
    loadData()
  }
}

const handleNextPage = () => {
  const totalPages = Math.ceil(pagination.value.total / pagination.value.size)
  if (pagination.value.current < totalPages) {
    pagination.value.current++
    loadData()
  }
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true

    const params: DocumentQueryParams = {
      title: searchForm.value.title || undefined,
      current: pagination.value.current,
      size: pagination.value.size,
    }

    // 时间筛选处理
    if (timeValue.value) {
      const parts = timeValue.value.split('-')
      const Y = parts[0]
      const M = parts[1]
      const D = parts[2]

      if (timeModeIndex.value === 0) {
        // 年
        ;(params as any).startTime = `${Y}-01-01T00:00:00`
        ;(params as any).endTime = `${Y}-12-31T23:59:59`
      } else if (timeModeIndex.value === 1) {
        // 月
        const lastDay = new Date(parseInt(Y), parseInt(M), 0).getDate()
        ;(params as any).startTime = `${Y}-${M}-01T00:00:00`
        ;(params as any).endTime = `${Y}-${M}-${String(lastDay).padStart(2, '0')}T23:59:59`
      } else {
        // 日
        ;(params as any).startTime = `${Y}-${M}-${D}T00:00:00`
        ;(params as any).endTime = `${Y}-${M}-${D}T23:59:59`
      }
    }

    const response = await getApprovalDocumentRecords(params)

    if (response.code === 200) {
      const data = response.data
      approvalList.value = data?.records || data || []
      pagination.value.total = data?.total || approvalList.value.length
      console.log('[已审批发文记录加载成功]', approvalList.value.length)
    } else {
      throw new Error(response.message || '加载失败')
    }
  } catch (error: any) {
    console.error('[加载已审批发文记录失败]', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none',
    })
  } finally {
    loading.value = false
  }
}

// 页面加载
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.my-approval-send-page {
  height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;

  /* 顶部导航 */
  .nav-header {
    background: #1678ff;
    padding: 46px 32rpx 20rpx 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: white;
    flex-shrink: 0;

    .nav-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .nav-center {
      flex: 1;
      text-align: center;

      .nav-title {
        font-size: 36rpx;
        font-weight: bold;
      }
    }

    .nav-right {
      min-width: 22px;
    }
  }

  /* 搜索区域 */
  .search-section {
    background: white;
    position: relative;
    z-index: 3;
    flex-shrink: 0;

    .search-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 24rpx 32rpx;
      cursor: pointer;
      transition: background 0.3s;

      &:active {
        background: #f8f9fa;
      }

      .search-header-left {
        display: flex;
        align-items: center;
        gap: 12rpx;

        .search-header-title {
          font-size: 28rpx;
          font-weight: 600;
          color: #333;
        }
      }

      .search-header-right {
        display: flex;
        align-items: center;
        gap: 8rpx;

        .expand-text {
          font-size: 26rpx;
          color: #999;
        }
      }
    }

    .search-form {
      display: flex;
      flex-direction: column;
      gap: 20rpx;
      padding: 24rpx 32rpx;
      border-top: 1rpx solid #f0f0f0;

      .form-row {
        display: flex;
        align-items: center;
        width: 100%;

        .search-input {
          flex: 1;
          height: 80rpx;
          padding: 0 24rpx;
          border: 1rpx solid #e5e7eb;
          border-radius: 12rpx;
          font-size: 28rpx;
          background: #f8f9fa;
        }
      }

      .time-filter-row {
        display: flex;
        align-items: center;
        gap: 16rpx;

        .filter-label {
          font-size: 28rpx;
          color: #333;
          white-space: nowrap;
          min-width: 120rpx;
        }

        .time-picker-group {
          flex: 1;
          display: flex;
          align-items: center;
          gap: 12rpx;
          position: relative;

          .time-mode-picker,
          .time-value-picker {
            flex: 1;
          }

          .time-mode-picker {
            max-width: 120rpx;
          }

          .time-value-picker {
            flex: 2;
          }

          .picker-input {
            padding: 16rpx 20rpx;
            background: #f8f9fa;
            border-radius: 12rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border: 1rpx solid #e5e7eb;
            font-size: 28rpx;
            color: #333;
            transition: all 0.3s ease;

            &:active {
              background: #eef2f7;
              border-color: #1678ff;
            }

            &.mode-picker {
              text-align: center;
            }

            &.value-picker {
              .time-text {
                font-size: 28rpx;
                color: #333;

                &.placeholder {
                  color: #999;
                }
              }
            }
          }

          .clear-btn {
            position: absolute;
            right: 12rpx;
            z-index: 10;
            padding: 4rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 50%;
          }
        }
      }

      .search-buttons {
        display: flex;
        gap: 16rpx;
        justify-content: flex-end;

        .search-btn,
        .reset-btn {
          padding: 16rpx 32rpx;
          border-radius: 12rpx;
          font-size: 26rpx;
          text-align: center;
        }

        .search-btn {
          background: #1678ff;
          color: white;
        }

        .reset-btn {
          background: #f3f4f6;
          color: #666;
        }
      }
    }
  }

  /* 统计卡片 */
  .stats-section {
    padding: 24rpx 32rpx;
    flex-shrink: 0;

    .stat-card {
      background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
      border-radius: 16rpx;
      padding: 32rpx;
      text-align: center;
      box-shadow: 0 8rpx 24rpx rgba(103, 194, 58, 0.3);

      .stat-value {
        display: block;
        font-size: 56rpx;
        font-weight: bold;
        color: white;
        margin-bottom: 8rpx;
      }

      .stat-label {
        font-size: 26rpx;
        color: rgba(255, 255, 255, 0.9);
      }
    }
  }

  /* 列表区域 */
  .list-section {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    padding: 20rpx 32rpx;

    .loading-state {
      text-align: center;
      padding: 60rpx 0;

      .loading-text {
        font-size: 28rpx;
        color: #999;
      }
    }

    .approval-list {
      flex: 1;
      overflow-y: auto;

      .approval-item {
        background: white;
        border-radius: 16rpx;
        padding: 24rpx;
        margin-bottom: 16rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
        transition: all 0.3s ease;

        &:active {
          opacity: 0.8;
        }

        .item-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16rpx;

          .item-title {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 12rpx;
            flex-wrap: wrap;

            .title-text {
              font-size: 28rpx;
              font-weight: 600;
              color: #333;
              flex: 1;
              min-width: 0;
            }

            .category-badge {
              padding: 6rpx 16rpx;
              border-radius: 8rpx;
              font-size: 20rpx;
              background: #ecf5ff;
              border: 1px solid #d9ecff;
              flex-shrink: 0;

              .badge-text {
                color: #1890ff;
                font-size: 20rpx;
              }
            }

            .category-badge-party {
              padding: 6rpx 16rpx;
              border-radius: 8rpx;
              font-size: 20rpx;
              background: #f0f9eb;
              border: 1px solid #e1f3d8;
              flex-shrink: 0;

              .badge-text {
                color: #67c23a;
                font-size: 20rpx;
              }
            }
          }

          .item-time {
            font-size: 22rpx;
            color: #ccc;
            flex-shrink: 0;
            margin-left: 4px;
          }
        }

        .item-content {
          margin-bottom: 16rpx;

          .item-desc {
            display: block;
            font-size: 24rpx;
            color: #999;
            line-height: 1.5;
            margin-bottom: 6rpx;
          }
        }

        .item-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .item-info {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 16rpx;
            flex-wrap: wrap;

            .info-text {
              font-size: 22rpx;
              color: #ccc;
            }
          }

          .item-actions {
            display: flex;
            gap: 20rpx;

            .action-btn {
              padding: 10rpx 20rpx;
              border-radius: 8rpx;
              font-size: 30rpx;
              color: #666;
              background: #f5f7fa;
              display: flex;
              align-items: center;
              justify-content: center;

              &.primary {
                background: #1678ff;
                color: white;
              }
            }
          }
        }
      }
    }

    .empty-state {
      text-align: center;
      padding: 80rpx 0;

      .empty-icon {
        font-size: 80rpx;
        display: block;
        margin-bottom: 24rpx;
      }

      .empty-text {
        font-size: 28rpx;
        color: #999;
      }
    }

    /* 分页固定底部 */
    .pagination-section {
      padding: 20rpx 0;
      background: white;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-shrink: 0;
      border-top: 1rpx solid #e5e7eb;
      border-radius: 12rpx;
      margin-top: 16rpx;
      padding: 20rpx 24rpx;
      box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.04);

      .pagination-info {
        font-size: 26rpx;
        color: #666;
        font-weight: 500;
      }

      .pagination-buttons {
        display: flex;
        gap: 12rpx;

        .page-btn {
          padding: 12rpx 24rpx;
          border-radius: 12rpx;
          font-size: 26rpx;
          background: #1678ff;
          color: white;
          transition: all 0.3s ease;

          &:active:not(.disabled) {
            opacity: 0.8;
            transform: scale(0.95);
          }

          &.disabled {
            opacity: 0.4;
            background: #d1d5db;
            color: #9ca3af;
          }
        }
      }
    }
  }
}
</style>
